<template>
  <div class="history-container">
    <div class="history-header">
      <h1>生成历史</h1>
      <p>查看您的3D模型生成记录（仅显示24小时内的记录）</p>
      <div class="history-notice">
        <span class="notice-icon">📝</span>
        <span>历史记录只可以下载查看，无法在线预览</span>
      </div>
    </div>

    <div class="history-content">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载历史记录中...</p>
      </div>

      <div v-else-if="histories.length === 0" class="empty-state">
        <div class="empty-icon">📝</div>
        <h3>暂无生成记录</h3>
        <p>开始生成您的第一个3D模型吧！</p>
      </div>

      <div v-else class="history-list">
        <div v-for="history in histories" :key="history.taskId" class="history-item">
          <div class="history-info">
            <div class="history-title">
              <span v-if="history.prompt" class="prompt-text">{{ history.prompt }}</span>
              <span v-else-if="history.imageFileName" class="image-text">图片: {{ history.imageFileName }}</span>
              <span v-else class="unknown-text">未知类型</span>
            </div>
            <div class="history-meta">
              <span class="format">{{ history.resultFormat }}</span>
              <span v-if="history.enablePBR" class="pbr">PBR</span>
              <span class="time">{{ formatDate(history.createdAt) }}</span>
            </div>
          </div>

          <div class="history-status">
            <div v-if="history.status === 'RUN'" class="status-running">
              <div class="spinner"></div>
              <span>生成中...</span>
            </div>
            <div v-else-if="history.status === 'DONE'" class="status-success">
              <span class="success-icon">✅</span>
              <span>已完成</span>
            </div>
            <div v-else-if="history.status === 'FAIL'" class="status-failed">
              <span class="error-icon">❌</span>
              <span>生成失败</span>
            </div>
          </div>

          <div class="history-actions">
            <button v-if="history.status === 'DONE' && history.resultUrl" 
                    @click="downloadModel(history.resultUrl)" 
                    class="download-button">
              下载模型
            </button>
            <button v-if="history.status === 'FAIL'" 
                    @click="showError(history.errorMessage)" 
                    class="error-button">
              查看错误
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { modelAPI } from '@/services/api'

export default {
  name: 'HistoryView',
  data() {
    return {
      histories: [],
      loading: true
    }
  },
  methods: {
    async loadHistory() {
      this.loading = true
      try {
        const result = await modelAPI.getHistory()
        if (result.success) {
          this.histories = result.data || []
        } else {
          console.error('加载历史记录失败:', result.error)
        }
      } catch (error) {
        console.error('加载历史记录异常:', error)
      } finally {
        this.loading = false
      }
    },
    
    downloadModel(url) {
      // 下载模型文件
      const link = document.createElement('a')
      link.href = url
      link.download = `3d-model-${Date.now()}.glb`
      link.click()
    },
    
    showError(errorMessage) {
      alert(`生成失败: ${errorMessage}`)
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知'
      let date
      if (typeof dateString === 'string') {
        const normalized = dateString.replace(' ', 'T')
        date = new Date(normalized)
      } else if (Array.isArray(dateString)) {
        const [year, month, day, hour = 0, minute = 0, second = 0] = dateString
        if (year && month && day) {
          date = new Date(year, month - 1, day, hour, minute, second)
        }
      }
      if (!date || isNaN(date.getTime())) return '未知'
      return date.toLocaleString('zh-CN')
    }
  },
  mounted() {
    this.loadHistory()
    // 每30秒刷新一次状态
    this.refreshInterval = setInterval(() => {
      this.loadHistory()
    }, 30000)
  },
  beforeUnmount() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval)
    }
  }
}
</script>

<style scoped>
.history-container {
  min-height: calc(100vh - 64px);
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.history-header {
  text-align: center;
  margin-bottom: 30px;
}

.history-header h1 {
  color: #333;
  font-size: 28px;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.history-header p {
  color: #666;
  font-size: 14px;
  margin: 0 0 10px 0;
}

.history-notice {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: #fff7e6;
  border: 1px solid #ffe7ba;
  color: #ad6800;
  border-radius: 6px;
  font-size: 13px;
}

.notice-icon {
  font-size: 14px;
}

.history-content {
  max-width: 800px;
  margin: 0 auto;
}

.loading-state {
  text-align: center;
  padding: 60px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e1e5e9;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-state p {
  color: #666;
  font-size: 16px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.empty-state h3 {
  color: #333;
  font-size: 20px;
  margin: 0 0 10px 0;
}

.empty-state p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 20px;
  transition: transform 0.2s ease;
}

.history-item:hover {
  transform: translateY(-2px);
}

.history-info {
  flex: 1;
}

.history-title {
  margin-bottom: 8px;
}

.prompt-text, .image-text, .unknown-text {
  font-weight: 500;
  color: #333;
  font-size: 16px;
}

.prompt-text {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-meta {
  display: flex;
  gap: 12px;
  align-items: center;
}

.format, .pbr, .time {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
}

.format {
  background: #e3f2fd;
  color: #1976d2;
}

.pbr {
  background: #f3e5f5;
  color: #7b1fa2;
}

.time {
  background: #f5f5f5;
  color: #666;
}

.history-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-running {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #ff9800;
  font-weight: 500;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #ffcc80;
  border-top: 2px solid #ff9800;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.status-success {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4caf50;
  font-weight: 500;
}

.status-failed {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #f44336;
  font-weight: 500;
}

.history-actions {
  display: flex;
  gap: 8px;
}

.download-button, .error-button {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.download-button {
  background: #4caf50;
  color: white;
}

.download-button:hover {
  background: #45a049;
}

.error-button {
  background: #f44336;
  color: white;
}

.error-button:hover {
  background: #d32f2f;
}

@media (max-width: 768px) {
  .history-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .history-meta {
    flex-wrap: wrap;
  }
  
  .history-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
